package cn.sc.summer.core.util;

import cn.hutool.core.util.StrUtil;
import cn.sc.summer.constant.token.TokenConstant;
import cn.sc.summer.exception.exceptions.CommonException;
import cn.sc.summer.exception.hodler.SpringContextHolder;
import cn.sc.summer.token.enums.LoginTypeEnum;
import cn.sc.summer.token.po.UserDetailX;
import cn.sc.summer.token.po.UserTokenInfo;
import cn.sc.summer.token.util.UserUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;
import java.util.Optional;

/**
 * 用户工具类
 *
 * @author a-xin
 */
@Slf4j
@Component
public class SpringSecurityUserUtil extends UserUtil {

    /**
     * 获取登录用户认证信息
     *
     * @return 认证信息
     */
    public static UserTokenInfo getLoginInfo() {
        return getUserTokenInfo(getLoginToken());
    }

    /**
     * 获取登录用户
     *
     * @return LoginUserDTO
     */
    public static UserDetailX getLoginUser() {
        return getLoginUser(getLoginToken());
    }

    /**
     * 获取是否用户登录状态
     *
     * @return 是否登录
     */
    public static Boolean hasLoginStatus() {
        try {
            Optional<UserDetailX> loginUserOption = Optional.ofNullable(getLoginUser());
            if (loginUserOption.isPresent()) {
                return Boolean.TRUE;
            }
            return Boolean.FALSE;
        } catch (CommonException e) {
            return Boolean.FALSE;
        }
    }

    /**
     * 获取当前用户登录方式类型
     *
     * @return 登录方式
     */
    public static LoginTypeEnum getUserLoginType() {
        return LoginTypeEnum.getBySlogan(Optional.ofNullable(Objects.requireNonNull(getUserTokenInfo(getLoginToken())).getLoginType()).orElse(LoginTypeEnum.WEB.getType()));
    }

    /**
     * 获取用户ID
     *
     * @return 用户ID
     */
    public static String getLoginUserId() {
        return getLoginUser().getUserId();
    }

    /**
     * 获取用户区域ID
     *
     * @return 区域ID
     */
    public static String getLoginUserTenantId() {
        return getLoginUser().getTenantId();
    }

    /**
     * 获取登录用户token
     *
     * @return token
     */
    public static String getLoginToken() {
        try {
            HttpServletRequest request = SpringContextHolder.getHttpServletRequest();
            String token = request.getHeader(TokenConstant.ACCESS_TOKEN);
            if (StrUtil.isBlank(token)) {
                throw new CommonException("Have no login status！");
            }
            return token;
        } catch (Exception e) {
            throw new CommonException("Have no login status: " + e.getMessage(), e);
        }
    }

}
